<?php include_once "../config/sessioninclude.php"; ?> 
<html><head><title><?php echo $mysitename ?> Open_ID login example</title></head>
<body><?php include("navigation.php"); ?>
<br />This is the page rpxnow should be kicked back too for confirmation of user info.<br />
<?php
// rpxnow.com should have had the user pass us a token.  Lets tie the token into the session to ID the user.
if ($catdebug) echo "\n>>>>Got Here 1\n";
if(isset($_POST['token'])) // we have a token should check it's from kopykat.rpxnow.com
{
	$token = $_POST['token'];
	$_SESSION['token'] = $_POST['token'];
	if ($catdebug) echo "\n>>>>Got Here 2\n";
	if ($catdebug) echo "\nNew TOKEN posted....";
}
if ($catdebug) {
	echo "\n>>>>Got Here 3\n";
	echo "\nToken: ". $_SESSION['token'];
	echo "\nDestroy:    " . $destroy;
	echo "\nSessionID: " . $_SESSION['sessionid'];
	echo "\nSafty:       " . $_SESSION['safty'];
	echo "\nView:        " . $_SESSION['views'];
}

//For a production script it would be better to include the apiKey in from a file outside the web root to enhance security.
$rpx_api_key = '2ce7f5f83851133180d781c6fa149fc197c2b73d';

if(strlen($_SESSION['token']) == 40) 
{//test the length of the token; it should be 40 characters
	if ($catdebug) echo "\n>>>>Got Here 4\n";
	$post_data = array('token'  => $_SESSION['token'],
                     'apiKey' => $rpx_api_key,
                     'format' => 'json',
                     'extended' => 'false'); //Extended is not available to Basic.
	if ($catdebug) print_r($post_data);
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_URL, 'https://rpxnow.com/api/v2/auth_info');
	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_FAILONERROR, true);
	$result = curl_exec($curl);
	if ($catdebug) {
		echo "\n>>>>Got Here 5\n";
		print_r($result);
	}
	if ($result == false) {
		echo "\n>>>>Got Here 5-error\n";
		echo "\n".'Curl error: ' . curl_error($curl);
		echo "\n".'HTTP code: ' . curl_errno($curl);
		echo "\n"; var_dump($post_data);
	}
	curl_close($curl);
	$auth_info = json_decode($result, true);
	
	if ($auth_info['stat'] == 'ok') {
		if ($catdebug) {
			echo "\n>>>>Got Here 6\n";
			echo "\n auth_info: \n";
			var_dump($auth_info);
		}
		$rpx[1] = $auth_info['profile']['verifiedEmail'];
		$rpx[2] = $auth_info['profile']['displayName'];
		$rpx[3] = $auth_info['profile']['preferredUsername'];
		$rpx[4] = $auth_info['profile']['url'];
		$rpx[5] = $auth_info['profile']['providerName'];
		$rpx[6] = $auth_info['profile']['identifier'];
		$rpx[7] = $auth_info['profile']['email'];
		if ($catdebug) {
			echo "\nSome stuff to pass along....";
			echo "\nname: " . $rpx[2];
			echo "\nYour " . $rpx[5] . " account identified you.";
			echo "\nToken: " . $token;
			echo "\nSessionViews: " . $_SESSION['views'];
			echo "\nSessionVID: " . $_SESSION['sessionid'];
			echo "\nChecking User...";
		}
		$rpxuseruid = md5($rpx[7] . $rpx[6] . $rpx[5]);
		if ($catdebug) echo "\nHashed: " . $rpxuseruid;
		//OK... we got a session and a User auth data
		// NOW some Database stuff
		if ($catdebug) echo "\n myuseruid: " . $myuseruid . "\n<br/>";
		$link = mysql_connect($linkhost,$linkuser,$linkpwd) or die('Cannot connect to the DB');
		mysql_select_db('kopykat',$link) or die('Cannot select the DB');
		/* grab the session data from the db */
		$query = "SELECT * FROM kksession WHERE sid = '$rpxuseruid'";	
		$retid = mysql_query($query,$link) or die('Error query was:  '.$query);

		// check for error
		if ($catdebug) echo "\n>>>>Got Here 7\n";
		if (!$retid) { echo( mysql_error()); 
		} else {
			if ($catdebug) {
				echo "\n>>>>Got Here 8\n";
				echo "\nGot into the kkauth db stuff.\n";
				while($row = mysql_fetch_array($retid))
				{
					echo print_r($row);
					echo "<br />";
				}
				echo "\n>>>>Got Here 9\n";
				echo "\nInsert the stuff.\n";
			}
			//This SQL call is unique to the handoff of info from rpx  so we will not put this call into the connect_cid
			$SQL = "INSERT INTO kkauth ";
			$SQL = $SQL . " (kkuidhash, token, provider, identifier, URL, email, name) VALUES ";
			$SQL = $SQL . " ('$rpxuseruid','$token','$rpx[5]','$rpx[6]','$rpx[4]','$rpx[7]','$rpx[3]') ";
			$SQL = $SQL . " ON DUPLICATE KEY UPDATE ";
			$SQL = $SQL . " kkuidhash = '$rpxuseruid' ";
			//execute SQL statement
			$result = mysql_query($SQL,$link);
			// check for error
			if (!$result) 
			{ 
				echo "\n>>>>Got Here 10 - Return User Detected\n";
				echo("ERROR: " . mysql_error() . "\n$SQL\n");
				echo("\n Need some sort of Welcome Back and check the data.");
			} else { 
				echo "\n>>>>Got Here 10 - New User Detected\n";
				echo ("<p><b>New Link Added</b></p>\n");	
			}
		}
		if ($catdebug) {
			echo "\n>>>>Got Here 11\n";
			echo "\nHave both USER and a Session now... lets tie them together.";
		}
		$sid = $_SESSION['sessionid'];
		$uid = $rpxuseruid;
		$SQL = " INSERT INTO kksession ";
		$SQL = $SQL . " (sid, uid, expire) VALUES ";
		$SQL = $SQL . " ('$sid','$uid','$expire') ON DUPLICATE KEY UPDATE sid = '$sid' ";
		//execute SQL statement
		$result = mysql_query($SQL,$link);
		// check for error
		if (!$result) 
		{ 
			echo "\n>>>>Got Here 11 - Return Session Detected\n";
			echo("ERROR: " . mysql_error() . "\n$SQL\n");
			echo("\n Need some sort of Session detection.");
		} else { 
			echo "\n>>>>Got Here 11 - New Session Detected\n";
			echo ("<p><b>New Session.</b></p>\n");				
		}
		mysql_close($link); 
	} 
}
/*		$rpx[1] = $auth_info['profile']['verifiedEmail'];
		$rpx[2] = $auth_info['profile']['displayName'];
		$rpx[3] = $auth_info['profile']['preferredUsername'];
		$rpx[4] = $auth_info['profile']['url'];
		$rpx[5] = $auth_info['profile']['providerName'];
		$rpx[6] = $auth_info['profile']['identifier'];
		$rpx[7] = $auth_info['profile']['email'];
*/
if ($catdebug) {
echo "</br><h1>OK... this is the confirm stuff to put the user into the structure.</h1></br>";
echo "I'm pulling the info from rpx, I should be pulling it from the db... something to do later...</br>";
echo "<table border='1'><tr><th>Info Type</th><th>my Data</th></tr>";
echo "<tr><td>verifiedEmail</td><td>$rpx[1]</td></tr>";
echo "<tr><td>displayName</td><td>$rpx[2]</td></tr>";
echo "<tr><td>preferredUsername</td><td>$rpx[3]</td></tr>";
echo "<tr><td>url</td><td>$rpx[4]</td></tr>";
echo "<tr><td>providerName *Required</td><td>$rpx[5]</td></tr>";
echo "<tr><td>identifier *Required</td><td>$rpx[6]</td></tr>";
echo "<tr><td>email *Required</td><td>$rpx[7]</td></tr>";
echo "</table></br>";
};

printf('<meta http-equiv="refresh" content="0; URL=%s" />', $mysitebase); 

?>

</body></html>